package com.cysyz.service.product.impl

import com.cysyz.dao.Conds
import com.cysyz.entity.product.Brand
import com.cysyz.mycommonservice.BaseService
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.UUID
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional
class BrandServiceImpl extends BaseService implements BrandService{
	
	override list(Brand brand, int currentPage, int maxResult) {
		var conds = new Conds()
		if (!brand.name.nullOrEmpty) {
			conds.addFilter("name", "like", "%" + brand.name + "%")
		}
		conds.addFilter("visible", true)
		conds.setOrderBy("name desc")
		return dao.listPaging(brand.class, conds, currentPage, maxResult)
	}
	
	override add(Brand brand, String inputFileName, byte[] inputFileData, String physicalSavePath) {
		checkNullOrEmpty(brand, "name")
		saveLogoFile(inputFileName, physicalSavePath, inputFileData, brand)
		dao.save(brand)
	}

	def private saveLogoFile(String inputFileName, String physicalSavePath, byte[] inputFileData, Brand brand) {
		val inputFileExt = inputFileName.substring(inputFileName.lastIndexOf(".") + 1)
		val logoPathPrefix = '''/image/brand«new SimpleDateFormat("/yyyy/MM/dd/HH/").format(new Date())»''' 
		val saveFileName = '''«UUID.randomUUID».«inputFileExt»'''
		println(saveFileName)
		val fileSaveDir = '''«physicalSavePath»/«logoPathPrefix»'''
		val urlPath = '''«logoPathPrefix»«saveFileName»'''
		val file = new File(fileSaveDir)
		if (!file.exists) {
			file.mkdirs
		}
		var BufferedOutputStream bops
		try {
			bops = new BufferedOutputStream(new FileOutputStream(new File(file, saveFileName)))				
			bops.write(inputFileData)
		} finally {
			bops?.close			
		}
		brand.setLogopath(urlPath)
	}
	
	override add(Brand brand) {
		checkNullOrEmpty(brand, "name")
		dao.save(brand)
	}
	
	override edit(Brand brand, String inputFileName, byte[] inputFileData, String physicalSavePath) {
		checkNullOrEmpty(brand, "name")
		var brandDB = dao.get(brand.class, brand.brandid)
		brandDB.name = brand.name
		saveLogoFile(inputFileName, physicalSavePath, inputFileData, brandDB)
	}
	override edit(Brand brand) {
		checkNullOrEmpty(brand, "name")
		var brandDB = dao.get(brand.class, brand.brandid)
		brandDB.name = brand.name
	}
}